<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="任务编码" prop="taskNo">
        <el-input
          v-model="queryParams['task.taskNo']"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="接收方类型" label-width="90px" prop="roleType">
        <el-select v-model="queryParams.roleType">
          <el-option :value="1" label="平台"></el-option>
          <el-option :value="2" label="代理"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="接收方" prop="companyName" v-if="organizationType === 3">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入接收方"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="发票类型" prop="invoiceType">
        <el-select v-model="queryParams['task.invoiceType']">
          <el-option :value="2" label="普票"></el-option>
          <el-option :value="1" label="专票"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发票类目" prop="invoiceCatagory" v-if="organizationType === 4">
        <el-input
          v-model="queryParams['task.invoiceCatagory']"
          placeholder="请输入发票类目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          size="mini"-->
<!--          @click="handleInvoice"-->
<!--        >批量开票-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="separateList" @select="handleSelectionChange" @select-all="handleSelectionAllChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="任务编码" align="center" prop="task.taskNo" min-width="180" show-overflow-tooltip/>
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="180">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" @click="detailOpen=true;taskNo = row.taskNo">{{ row.task.taskName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="接收方类型" align="center" prop="organizationType" min-width="110" show-overflow-tooltip>
        <template slot-scope="{ row }">
          {{row.organizationType===1?'平台':row.organizationType===2?'代理':''}}
        </template>
      </el-table-column>
      <el-table-column label="接收方" align="center" prop="companyName" min-width="180" show-overflow-tooltip/>
      <el-table-column label="开票类型" align="center" prop="task.invoiceType" min-width="100" >
        <template slot-scope="{ row }">
          {{row.task.invoiceType===1?'专票':row.task.invoiceType===2?'普票':''}}
        </template>
      </el-table-column>
      <el-table-column label="开票类目" align="center" prop="task.invoiceCatagory" min-width="180">
        <template slot-scope="{ row }">
          <span v-if="organizationType === 3">
            {{handleInvoiceCatagory(row)}}
          </span>
          <span v-else> {{row.task.invoiceCatagory}} </span>
        </template>
      </el-table-column>
      <el-table-column label="分润金额" align="center" prop="separateAmount" />
      <el-table-column label="开票状态" align="center" prop="isInvoicing" width="100">
        <template slot-scope="{ row }">
          <el-tag style="cursor: pointer" type="success" v-if="row.isInvoicing === 0">待开票</el-tag>
        </template>
      </el-table-column>
      <template slot="empty">
        <el-empty :image-size="100"></el-empty>
      </template>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" destroy-on-close title="任务详情" :visible.sync="detailOpen" size="80%" append-to-body>
      <taskDetail :id="taskNo"></taskDetail>
    </el-drawer>
    <el-drawer :wrapperClosable="false" :close-on-press-escape="false"  title="开票" :visible.sync="invoiceOpen" size="65%" append-to-body>
      <el-row :gutter="20">
        <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
          <pane size="28">
            <div class="head-container">
            </div>
            <div class="head-container">
              <el-tree highlight-current @node-click="handleNodeClick" :default-expanded-keys="defaultExpandedKeys" :data="invoices" ref="tree" node-key="key" :props="{children:'invoices'}">
                    <span class="custom-tree-node" slot-scope="{ node, data }">

                       <span v-if="node.level === 1">{{ data.companyName }}（{{data.organizationType===1?'平台':data.organizationType===2?'代理':''}}）</span>
                       <span v-else>{{ data.invoiceCatagory }}</span>
                    </span>
              </el-tree>
            </div>
          </pane>
          <pane size="72">
            <el-col>
              <el-descriptions title="申请信息">
                <el-descriptions-item label="申请发票类型">普票</el-descriptions-item>
                <el-descriptions-item :span="2" label="申请类目">{{ invoiceInfo.invoiceCatagory }}
                </el-descriptions-item>
                <el-descriptions-item label="税额/元">{{ formattedTotal(invoiceInfo.taxAmount) }}</el-descriptions-item>
                <el-descriptions-item label="不含税金额/元">{{ formattedTotal(invoiceInfo.taskAmount) }}
                </el-descriptions-item>
                <el-descriptions-item label="价税合计/元">{{ formattedTotal(invoiceInfo.invoiceAmount) }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </pane>
        </splitpanes>
      </el-row>
      <div class="dialog-footer">
        <el-button :loading="invoiceLoading" type="primary" @click="subInvoice">立即提交</el-button>
        <el-button :loading="invoiceLoading" @click="invoiceOpen = false">取 消</el-button>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import store from '@/store'
import 'splitpanes/dist/splitpanes.css'
import { listTask } from '@/api/system/task'
import { Pane, Splitpanes } from 'splitpanes'
import { listSeparate } from "@/api/transfer/separate";
import { listTaxMarket } from '@/api/tax/taxMarket'
// import { listCooperateTsl } from '@/api/ecs/cooperateTsl'
// import taskDetail from '@/views/ecs/task/modules/detail.vue'
import { applyForPayslipInvoice } from '@/api/invoice/invoice'

export default {
  name: "Separate",
  components: { Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: true,
      tslLoading:false,
      tslOptions: [],
      taskOptions: [],
      merchantOptions:[],
      taskLoading: false,
      merchantLoading:false,
      showSearch: true,
      detailOpen:false,
      invoiceOpen:false,
      invoiceLoading:false,
      // 总条数
      total: 0,
      // 分润信息表格数据
      separateList: [],
      // 查询参数
      queryParams: {
        status:2,
        pageNum: 1,
        pageSize: 10,
        taskNo: null,
        roleType: null,
        merchantId: null,
        isInvoicing:0,
        companyName:null,
        'task.taskNo':null,
        'task.invoiceType':null,
        'task.invoiceCatagory':null,
      },
      taskNo:null,
      invoices:[],
      invoiceInfo:{},
      selectedRowKeys:[],
      defaultExpandedKeys:[],
      organizationType: store.getters.organizationType,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleNodeClick(v,d) {
      if (d.level === 2) {
        this.invoiceInfo = v
      }
    },
    /** 查询分润信息列表 */
    getList() {
      this.loading = true;
      listSeparate(this.queryParams).then(response => {
        this.separateList = response.rows;
        this.total = response.total;
        this.setSelected()
        this.loading = false;
      });
    },

    setSelected() {
      this.separateList.forEach(item => {
        const isSelected = this.selectedRowKeys.find(row => item.separateId === row.separateId)
        item._selected = isSelected
        if (isSelected) {
          this.$nextTick(() => {
            this.$refs.table.toggleRowSelection(item, isSelected)
          })
        }
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams['task.taskNo'] = null;
      this.queryParams['task.invoiceType'] = null
      this.queryParams['task.invoiceCatagory'] = null
      this.resetForm("queryForm");
      this.handleQuery();
    },


    handleSelectionChange(selection, row) {
      const isAdd = selection.some((selectRow) => selectRow.separateId === row.separateId)
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }
      this.handleRowChangeAll(row, isAdd)
    },

    handleSelectionAllChange(selection) {
      let isAdd = true
      let changeSelect = selection.slice()

      if (!changeSelect.length) {
        isAdd = false
        changeSelect = this.separateList.slice()
      }
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }

      for (let i = 0; i < changeSelect.length; i++) {
        const row = changeSelect[i]
        // 检查是否应该终止循环
        this.handleRowChangeAll(row, isAdd)
      }
    },
    /**
     * 处理行选择变更（全量处理）
     * @param {Object} row - 当前选择的行数据
     * @param {boolean} isAdd - 是否为添加操作
     * @returns {boolean} - 始终返回false以阻止默认行为
     */
    handleRowChangeAll(row, isAdd) {
      // 检查行是否已被选中
      const isRowSelected = this.isRowSelected(row);

      // 添加操作处理
      if (isAdd && !isRowSelected) {
        this.handleAddRow(row);

      }

      // 移除操作处理
      if (!isAdd && isRowSelected) {
        this.removeInvoiceData(row);
      }

      return false;
    },

    /**
     * 检查行是否已被选中
     * @param {Object} row - 行数据
     * @returns {boolean} - 是否选中
     */
    isRowSelected(row) {
      return this.selectedRowKeys.some(item => item.separateId === row.separateId);
    },

    /**
     * 处理添加行操作
     * @param {Object} row - 行数据
     */
    handleAddRow(row) {
      // 检查是否超过最大选择限制
      if (this.selectedRowKeys.length >= 1000) {
        this.$refs.table.toggleRowSelection(row, false);
        this.$message.warning('最多只能选择1000条记录');
        return;
      }

      // 查找或创建发票记录
      let invoice = this.findOrCreateInvoice(row);

      // 处理发票分类
      const categoryData = this.prepareCategoryData(row);
      this.updateInvoiceCategories(invoice, categoryData, row);

      // 添加到选中列表
      this.selectedRowKeys.push({ separateId: row.separateId });
    },

    /**
     * 查找或创建发票记录
     * @param {Object} row - 行数据
     * @returns {Object} - 发票记录
     */
    findOrCreateInvoice(row) {
      let invoice = this.invoices.find(item => item.receiverOrganizationId === row.organizationId);

      if (!invoice) {
        invoice = {
          taxOrganizationId:row.taxOrganizationId,
          invoices: [],
          key: row.organizationId,
          taskNo:row.taskNo,
          organizationType:row.organizationType,
          receiverOrganizationId: row.organizationId,
          companyName: row.companyName,
        };
        this.invoices.push(invoice);
      }

      return invoice;
    },

    /**
     * 从发票数据中移除相关信息
     * @param {Object} row - 行数据
     */
    /**
     * 从发票数据中移除相关信息
     * @param {Object} row - 行数据
     */
    removeInvoiceData(row) {
      // 从选中行列表中移除
      this.selectedRowKeys = this.selectedRowKeys.filter(item => item.separateId !== row.separateId);

      // 从发票数据中移除相关信息
      const invoiceIndex = this.invoices.findIndex(item => item.receiverOrganizationId === row.organizationId);
      if (invoiceIndex !== -1) {
        const invoice = this.invoices[invoiceIndex];

        // 准备要扣除的金额

        // 处理每个分类
        invoice.invoices.forEach(category => {
            // 只处理包含当前行数据分类的金额
          // 检查该分类是否包含此工资单
          const separateIndex = category.separates.findIndex(separate => separate.separateId === row.separateId);

          if (separateIndex !== -1) {

            const categoryData = this.calculateAmountData(row);


            // 扣除金额（使用整数运算）
            category.taskAmount = this.toFixedTwoDecimals(
              this.toInteger(category.taskAmount) - categoryData.taskAmount
            );

            category.taxAmount = this.toFixedTwoDecimals(
              this.toInteger(category.taxAmount) -  categoryData.taxAmountInCents
            );

            category.invoiceAmount = this.toFixedTwoDecimals(
              this.toInteger(category.invoiceAmount) -  categoryData.invoiceAmount
            );

              // return {
              //   ...category,
              //   taskAmount: this.subtractAndFormat(category.taskAmount, amountData.taskAmount),
              //   taxAmount: this.subtractAndFormat(category.taxAmount, amountData.taxAmount),
              //   invoiceAmount: this.subtractAndFormat(category.invoiceAmount, amountData.invoiceAmount),
              // };
            }
          })

        // 过滤掉没有工资单的分类
        invoice.invoices = invoice.invoices.filter(
          category => category.separates.length > 0
        );


        // 如果发票没有分类了，移除整个发票记录
        if (invoice.invoices.length === 0) {
          this.invoices.splice(invoiceIndex, 1);
        }
      }
    },

    /**
     * 判断行数据是否属于指定分类
     * @param {Object} row - 行数据
     * @param {Object} category - 分类数据
     * @returns {boolean} - 是否属于该分类
     */
    isRowInCategory(row, category) {
      // 由于移除了payslips，现在基于invoiceCatagory判断
      return category.invoiceCatagory === row.task.invoiceCatagory;
    },

    /**
     * 计算任务金额数据
     * @param {Object} row - 行数据
     * @returns {Object} - 金额数据
     */
    calculateAmountData(row) {

      // 金额转换为分（避免浮点精度问题）
      const invoiceAmount = this.toInteger(row.separateAmount);

      // 计算不含税金额和税额（使用整数运算）
      const taxRate = 6; // 6%
      const divisor = 100 + taxRate; // 106 for 6% tax

      // 计算不含税金额 (Y)
      const taskAmountInCents = Math.round((invoiceAmount * 100) / divisor);

      // 计算税额
      const taxAmountInCents = invoiceAmount - taskAmountInCents;
      return {
        taskAmount: taskAmountInCents,
        taxAmountInCents,
        invoiceAmount
      }
    },

    /**
     * 准备分类数据
     * @param {Object} row - 行数据
     * @returns {Object} - 分类数据
     */
    prepareCategoryData(row) {
      const amountData = this.calculateAmountData(row);

      return {
        ...amountData,
        invoiceType: row.task.invoiceType,
        invoiceCatagory: row.task.invoiceCatagory
      };
    },

    /**
     * 更新发票分类
     * @param {Object} invoice - 发票记录
     * @param {Object} categoryData - 分类数据
     * @param {Object} row - 行数据
     */
    updateInvoiceCategories(invoice, categoryData, row) {
      const { invoiceCatagory, invoiceType, taskAmount, taxAmountInCents, invoiceAmount } = categoryData;
      // 查找或创建分类记录
      let categoryRecordIndex = invoice.invoices.findIndex(
        item => item.invoiceCatagory === invoiceCatagory
      );
      let categoryRecord; // 提前声明变量

      if (categoryRecordIndex !== -1) {
        // 更新现有分类
        invoice.invoices[categoryRecordIndex] = {
          ...invoice.invoices[categoryRecordIndex],
          invoiceType,
          key: invoiceCatagory,
          taxAmount: this.addAndFormat(invoice.invoices[categoryRecordIndex].taxAmount, taxAmountInCents),
          taskAmount: this.addAndFormat(invoice.invoices[categoryRecordIndex].taskAmount, taskAmount),
          invoiceAmount: this.addAndFormat(invoice.invoices[categoryRecordIndex].invoiceAmount, invoiceAmount)
        };

        // 获取更新后的分类记录引用
        categoryRecord = invoice.invoices[categoryRecordIndex];
      } else {
        // 创建新分类
        categoryRecord = {
          invoiceType,
          invoiceCatagory,
          key: invoiceCatagory,
          invoiceAmount: this.toFixedTwoDecimals(invoiceAmount),
          taskAmount: this.toFixedTwoDecimals(taskAmount),
          taxAmount: this.toFixedTwoDecimals(taxAmountInCents),
          separates: []
        };

        invoice.invoices.push(categoryRecord);
      }

      // 添加工资单到分类
      categoryRecord.separates.push({ separateId: row.separateId, taskNo: row.taskNo });
    },
    /**
     * 安全地将两个数值相加并格式化为两位小数
     * @param {number|string} original - 原始值
     * @param {number|string} valueToAdd - 要添加的值
     * @returns {string} - 格式化后的结果
     */
    addAndFormat(original, valueToAdd) {
      valueToAdd = this.toFixedTwoDecimals(valueToAdd)
      return this.toFixedTwoDecimals(
        this.toInteger(original) + this.toInteger(valueToAdd)
      );
    },

    /**
     * 安全地将两个数值相减并格式化为两位小数
     * @param {number|string} original - 原始值
     * @param {number|string} valueToSubtract - 要减去的值
     * @returns {string} - 格式化后的结果
     */
    subtractAndFormat(original, valueToSubtract) {
      return this.toFixedTwoDecimals(
        this.toInteger(original) - this.toInteger(valueToSubtract)
      );
    },
    handleInvoice() {
      if (this.selectedRowKeys.length === 0 || this.invoices.length === 0) {
        this.$message.warning('暂无数据')
        return
      }
      this.invoiceOpen = true
      this.handleNodeClick( this.invoices[0].invoices[0],{level:2})
      this.$nextTick(() => {
        this.defaultExpandedKeys = [this.invoices[0]]
        this.$refs.tree.setCurrentNode(this.invoices[0].invoices[0])
      })
    },
    subInvoice() {
      this.$modal.confirm('确定要提交这些任务吗？').then(() => {
        this.invoiceLoading = true
        this.invoiceLoading = true
        applyForPayslipInvoice(this.invoices).then(res => {
          this.selectedRowKeys = []
          this.invoices=[]
          this.invoiceLoading = false
          this.invoiceOpen = false
          this.getList()
        }).catch(() => {
          this.invoiceLoading = false
        })
      })
    },


    // 辅助方法：转换为两位小数的字符串
    toFixedTwoDecimals(amountInCents) {
      return (amountInCents / 100).toFixed(2)
    },

    // 辅助方法：转换为整数（处理金额）
    toInteger(value) {
      if (typeof value === 'number') return Math.round(value * 100)
      if (typeof value === 'string') return Math.round(parseFloat(value) * 100)
      return 0
    },
    formattedTotal(amount) {
      const formatter = new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })

      return formatter.format(amount)
    },
    handleInvoiceCatagory(row){
      if (row.organizationType === 1){
        row.task.invoiceCatagory = "信息技术服务*技术服务费"
      }else if (row.organizationType === 2){
        row.task.invoiceCatagory = "现代服务*推广服务费"
      }
      return row.task.invoiceCatagory
    }

  }
};
</script>
<style scoped lang="scss">
.dialog-footer{
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  height: 55px;
  padding: 10px 20px;
  position: absolute;
  justify-content: flex-end;
  background-color: #ffffff;
  box-shadow: 0 0 4px rgba(0, 21, 41, 0.35);
}
</style>
